package com.jucai.pppeiyouclient.weidget.pulltorefresh;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by UPC on 2017/3/28.
 */

public class PullToRefreshForRecyclerView extends RecyclerView implements PullToRefreshImp {

    public PullToRefreshForRecyclerView(Context context) {
        super(context);
    }

    public PullToRefreshForRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PullToRefreshForRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean pullDown() {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
        if (linearLayoutManager.getItemCount() == 0) {
            /**
             *  没有item的时候也可以下拉刷新
             */
            return true;
            /**
             * 防止下拉过猛头部还没回到弹到顶就点击item出现对空指针问题
             */
        } else if (linearLayoutManager.findFirstVisibleItemPosition() == 0 && getChildAt(0) != null
                && getChildAt(0).getTop() >= 0) {
            /**
             *  滑到ListView的顶部了
             */
            return true;
        } else
            return false;
    }

    @Override
    public boolean pullUp() {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();

        if (linearLayoutManager.getItemCount() == 0) {
            /**
             *  没有item的时候也可以上拉加载
             */
            return true;
        } else if (linearLayoutManager.findLastVisibleItemPosition() == (linearLayoutManager.getItemCount() - 1)) {
            /**
             *  滑到底部了
             */
            if (getChildAt(linearLayoutManager.findLastVisibleItemPosition() - linearLayoutManager.findFirstVisibleItemPosition()) != null
                    && getChildAt(
                    linearLayoutManager.findLastVisibleItemPosition()
                            - linearLayoutManager.findFirstVisibleItemPosition()).getBottom() <= getMeasuredHeight())
                return true;
        }
        return false;
    }
}
